package com.xin.beauty.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xin.beauty.pojo.dto.AdminPasswordDTO;
import com.xin.beauty.pojo.entity.Admin;
import com.xin.beauty.pojo.dto.AdminLoginDTO;
import com.xin.beauty.pojo.entity.AdminRole;
import com.xin.beauty.pojo.entity.Role;
import com.xin.beauty.pojo.entity.User;
import com.xin.beauty.pojo.query.AdminQuery;
import com.xin.beauty.pojo.query.UserQuery;
import com.xin.beauty.service.IAdminRoleService;
import com.xin.beauty.service.IAdminService;
import com.xin.beauty.service.impl.AdminRoleServiceImpl;
import com.xin.beauty.util.JwtUtil;
import com.xin.beauty.util.Result;
import com.xin.beauty.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Xin
 * @since 2025-04-14
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @Autowired
    private IAdminRoleService adminRoleService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminRoleServiceImpl adminRoleServiceImpl;

    @GetMapping("/selectAssignedRole/{adminId}")
    public Result selectAssignedRole(@PathVariable Long adminId) {
        Map<String, Object> map = adminService.selectAssignedRole(adminId);
        return Result.ok(map);
    }


    @PostMapping("/assignRole")
    public Result assignRole(Long adminId, Long[] roleIds) {
        adminService.assignRole(adminId, roleIds);
        return Result.ok("分配成功");
    }

    //Restful  GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    @GetMapping("/list")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET})
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public Result list(AdminQuery adminQuery) {
        System.out.println("AdminController.list");
        IPage<Admin> page = adminService.list(adminQuery);
        //Map<String, Object> map = new HashMap<>();
        //map.put("total", page.getTotal());
        //map.put("list", page.getRecords());
        return Result.ok(page);

        /*IPage<Admin> page = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getName()), "name", adminQuery.getName());
        queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getPhone()), "phone", adminQuery.getName());
        adminService.page(page, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        return Result.ok(map);*/
    }

    // /admin/deleteById?id=12
    // /admin/deleteById/12
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminService.removeById(id);
        return Result.ok("删除成功");
    }

    // /admin/deleteById/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        adminService.removeBatchByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回,服务端返回给浏览器的
    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {
        adminService.adminAdd(admin);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        adminService.updateById(admin);
        return Result.ok("修改成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginDTO adminLoginDTO) {
        //首先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get("captcha:" + adminLoginDTO.getUuid());
        if (ObjectUtils.isEmpty(captcha)) {
            return Result.error("验证码已经失效");
        }
        if (!captcha.equalsIgnoreCase(adminLoginDTO.getCaptcha())) {
            return Result.error("验证码错误");
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", adminLoginDTO.getName());
        Admin loginAdmin = adminService.getOne(queryWrapper);
        //判断用户名是否存在
        if (ObjectUtils.isEmpty(loginAdmin)) {
            return Result.error("用户名不存在");
        }

        //判断密码是否正确
        if (!loginAdmin.getPassword().equalsIgnoreCase(adminLoginDTO.getPassword())) {
            return Result.error("密码错误");
        }

        if(loginAdmin.getStatus() == 0){
            return Result.error("该用户已被禁用");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());//把id name传进去
        String token = JwtUtil.createToken(map);//给账号生成一个token
        return Result.ok("登录成功", token);//把这个token返回 token是一个字符串 前面加""
    }

    @GetMapping("/adminInfo")
    public Result adminInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("id");
        //Admin admin = adminService.getById(id);
        Map<String, Object> m= adminService.selectAdminPersmissionInfoById(id);
        return Result.ok(m);
    }

    @GetMapping("/admin")
    public Result admin(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("id");
        return Result.ok(id);
    }



    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody AdminPasswordDTO adminPasswordDTO,//可删
                                @RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
//        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Admin admin = adminService.getById(id);
        if (!admin.getPassword().equalsIgnoreCase(adminPasswordDTO.getOldPassword())) {
            return Result.error("旧密码错误");
        }

        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("password", adminPasswordDTO.getNewPassword());
        adminService.update(admin, updateWrapper);
        return Result.ok("更新成功");
    }


    @GetMapping("/userlist")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET})
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public Result userlist(AdminQuery adminQuery) {
        System.out.println("AdminController.list");
        IPage<Admin> page = adminService.userlist(adminQuery);
        return Result.ok(page);
    }


    @PostMapping("/useradd")
    public Result useradd(@RequestBody Admin admin) {
        adminService.useradd(admin);
        return Result.ok("添加成功");
    }

    @GetMapping("/doctorlist")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET})
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public Result doctorlist(AdminQuery adminQuery) {
        System.out.println("AdminController.list");
        IPage<Admin> page = adminService.doctorlist(adminQuery);
        return Result.ok(page);
    }


    @PostMapping("/doctoradd")
    public Result doctoradd(@RequestBody Admin admin) {
        adminService.doctoradd(admin);
        return Result.ok("添加成功");
    }


    @GetMapping("/selectNotAll")
    public Result selectNotAll() {
        return Result.ok(adminService.listNotAll());
    }


}

